package main

import (
	"flag"
	"fmt"
	"log"
	"myserver/handle"
	"myserver/parse"
	"myserver/util"
	"net/http"
	"os"
	uch "usrcenter/handler"

	"github.com/tabalt/gracehttp"
	"github.com/urfave/negroni"
)

var port = flag.String("port", "8080", "Use -port <PORT>")
var confFile = flag.String("file", "conf/server.yaml", "Use -file <FILE>")

func main() {

	flag.Parse()

	conf := parse.ServerConf{}
	err := conf.ParseFile(confFile)
	if err != nil {
		log.Fatalf("error: %v", err)
		os.Exit(1)
	}

	routerMap := make(map[string]util.FuncInfo, 100)

	fn := handle.New()
	for _, value := range fn {
		if value.Name != "" {
			routerMap[value.Name] = util.FuncInfo(value)
			log.Printf("name : %s, value :%v", value.Name, value)
		}
	}

	fn1 := uch.New()
	for _, value := range fn1 {
		if value.Name != "" {
			routerMap[value.Name] = util.FuncInfo(value)
			log.Printf("name : %s, value :%v", value.Name, routerMap[value.Name])
		}
	}
	mux := http.NewServeMux()
	mux.HandleFunc("/mm", func(w http.ResponseWriter, req *http.Request) {
		fmt.Fprintf(w, "Welcome to the home page!")
	})

	// register router handler from confFile
	for i := 0; i < len(conf.ServerBlocks); i++ {
		for j := 0; j < len(conf.ServerBlocks[i].LocationBlocks); j++ {
			locationStr := conf.ServerBlocks[i].LocationBlocks[j].MatchPath
			funcStrName := conf.ServerBlocks[i].LocationBlocks[j].Handler
			log.Printf("--- locationStr : %s", locationStr)
			log.Printf("--- funcStrName : %s", funcStrName)
			log.Printf("routerMap[%s] : %v", funcStrName, routerMap[funcStrName])
			funcName := routerMap[funcStrName].FuncName
			log.Printf("funcStrName : %s, addr : %v", funcStrName, routerMap[funcStrName])

			if funcName == nil {
				log.Fatalln("match function not found or nil ")
				os.Exit(1)
			}

			mux.HandleFunc(locationStr, funcName())
		}
	}

	// *** 使用negroni框架
	n := negroni.Classic() // Includes some default middlewares
	n.UseHandler(mux)
	gracehttp.ListenAndServe(":"+*port, n)
	// *** 使用negroni框架

	// 可以不使用任何框架，直接使用http包提供的能力
	//	gracehttp.ListenAndServe(":"+*port, mux)
}
